package com.vertxsample.samples.testgateway.nodeserver

import com.vertxsample.samples.core.db.HikariPoolUtil
import com.vertxsample.samples.core.web.BaseNodeVerticle
import com.zaxxer.hikari.HikariConfig
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.StaticHandler
import org.apache.logging.log4j.LogManager


class StarterVerticle(val options :JsonObject,val port:Int) : BaseNodeVerticle() {
     val logger = LogManager.getLogger(StarterVerticle::class.java!!.getName())
    override fun start(startFuture: Future<Void>) {
        //启动web
        startServer(startFuture ,options);
    }

    fun  startServer(startFuture:Future<Void>,options :JsonObject){


        var router = customRouter(vertx,options)
        logger.info("server running on "+port)
        vertx.createHttpServer().requestHandler({ handler -> router.handle(handler)}).listen(port){ result ->
            if (result.succeeded()) {
                startFuture.complete()
            } else {
                startFuture.fail(result.cause())
            }
        }
    }

    fun customRouter(vertx : Vertx,options :JsonObject) : Router {


        //数据配置
        val config = HikariConfig()


        config.jdbcUrl =options.getString("datasource.url")
        config.username = options.getString("datasource.username")
        config.password = options.getString("datasource.password")
        config.driverClassName = options.getString("datasource.driver-class-name")

        config.addDataSourceProperty("cachePrepStmts", "true")
        config.addDataSourceProperty("prepStmtCacheSize", "250")
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")

        val dslContext= HikariPoolUtil.getContext(HikariPoolUtil.getConnection(HikariPoolUtil.getDataSource(config))!!)

        var router = Router.router(vertx)

        //静态页面配置
        val staticHandler = StaticHandler.create("src/main/webapp")
        router.route("/*").handler(staticHandler);

        //配置健康检查
        router.get("/health").handler({c -> c.response().html().end("success")})

        try {
            //根据注解设置路由
            super.configRouterByAnnotation("com.vertxsample.samples.testweb.controller",router, dslContext);
        }catch (e:Exception){
            logger.error("",e)
        }


        return router
    }
    fun HttpServerResponse.html() : HttpServerResponse {
        return this.putHeader("content-type","text/html")
    }


}